package com.lagou.edu.controller;

import com.lagou.edu.callback.Callback;
import com.lagou.edu.callback.JsonData;
import com.lagou.edu.dao.ResumeDao;
import com.lagou.edu.pojo.Resume;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/account")
public class AccountController {

    /**
     * Spring容器和SpringMVC容器是有层次的（父子容器）
     * Spring容器：service对象+dao对象
     * SpringMVC容器：controller对象，，，，可以引用到Spring容器中的对象
     */


    @Autowired
    private ResumeDao resumeDao;


    @GetMapping("/queryAll")
    @ResponseBody
    public ModelAndView queryAll() {
        return new ModelAndView("/list");
    }

    @PostMapping("/queryAll")
    @ResponseBody
    public HashMap<String, Object> queryAll1(Long page,Integer limit) {
        HashMap<String, Object> map = new HashMap<>();
        Resume resume= new Resume();
        page=(page-1);
//        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page.intValue(), limit);
        Page<Resume> all = resumeDao.findAll(pageable);
        map.put("count", all.getTotalElements());
        Stream<Resume> resumeStream = all.get();
        map.put("data", resumeStream.collect(Collectors.toList()));
        map.put("code", 0);
        return map;
    }

    @GetMapping("/edit")
    public String edit(Long id, Model model) {
        Optional<Resume >optional=Optional.empty();
        if (id != null) {
            optional  = resumeDao.findById(id);
        }
        model.addAttribute("item", optional.orElse(new Resume()));
        return "/edit";
    }


    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(HttpServletRequest request,Resume resume) {
        resumeDao.save(resume);
        return Callback.success("success", "修改成功");
    }

    @PostMapping("/delete")
    @ResponseBody
    public JsonData delete(HttpServletRequest request,Resume resume,Long id) {
        resumeDao.delete(resume);
        return Callback.success("success", "删除成功");
    }
}
